package service

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"time"
)

// from page :https://cloud.tencent.com/developer/article/2086721
type BingImage struct {
	Bot           int    `json:"bot"`
	Copyright     string `json:"copyright"`
	CopyrightLink string `json:"copyrightlink"`
	Drk           int    `json:"drk"`
	EndDate       string `json:"enddate"`
	FullStartDate string `json:"fullstartdate"`
	Hs            []int  `json:"hs"`
	Hsh           string `json:"hsh"`
	Quiz          string `json:"quiz"`
	StartDate     string `json:"startdate"`
	Title         string `json:"title"`
	Top           int    `json:"top"`
	Url           string `json:"url"`
	UrlBase       string `json:"urlbase"`
	Wp            bool   `json:"wp"`
}

type BingToolTips struct {
	Loading  string `json:"loading"`
	Next     string `json:"next"`
	Previous string `json:"previous"`
	WallE    string `json:"walle"`
	WallS    string `json:"walls"`
}

type BingResponse struct {
	Images   []BingImage  `json:"images"`
	Tooltips BingToolTips `json:"tooltips"`
}

type Picture struct {
	Title     string `json:"title"`
	URL       string `json:"url"`
	Copyright string `json:"copyright"`
}

var picture *Picture
var lastTime time.Time

func GetPicture() *Picture {
	if picture != nil && isToday(lastTime) {
		return picture
	}
	lastTime = time.Now()
	picture = getNewPicture()
	return picture
}

func isToday(t time.Time) bool {
	now := time.Now() // 获取当前时间
	return t.Year() == now.Year() && t.Month() == now.Month() && t.Day() == now.Day()
}

func getNewPicture() *Picture {
	resp, err := http.Get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1")
	if err != nil {
		log.Fatal(err)
	}

	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			log.Fatal(err)
		}
	}(resp.Body)
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	response := BingResponse{}
	err = json.Unmarshal(body, &response)
	if err != nil {
		log.Fatal(err)
	}

	if len(response.Images) > 0 {
		image := response.Images[0]
		return &Picture{
			Title:     image.Title,
			Copyright: image.Copyright,
			URL:       "https://www.bing.com" + image.Url,
		}
	}

	return nil
}
